/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package delta.cart.web;

import delta.cart.bean.CartLocal;
import delta.emailer.EmailerLocal;
import entity.Orders;
import entity.Product;
import entity.ProductList;
import entity.Users;
import entity.Warehouse;
import facade.OrdersFacade;
import facade.OrdersFacadeLocal;
import facade.ProductListFacadeLocal;
import facade.UsersFacadeLocal;
import facade.WarehouseFacadeLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.mail.Address;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.persistence.RollbackException;
import javax.resource.NotSupportedException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 *
 * @author Kate
 */
@WebServlet(name = "ConfirmOrder", urlPatterns = {"/ConfirmOrder"})
public class ConfirmOrder extends HttpServlet {

    @EJB
    private ProductListFacadeLocal productListFacade;
    @EJB
    private WarehouseFacadeLocal warehouseFacade;
    @EJB
    private OrdersFacadeLocal ordersFacade;
    CartLocal cart;
    Users user;
    @Resource
    UserTransaction tx;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Orders order = new Orders();

            HttpSession session = request.getSession();
            cart = (CartLocal) session.getAttribute("cart");
            user = (Users) session.getAttribute("user");

            int id_user;
            String address;
            String email;
            Warehouse warehouse;
            BigDecimal productPrice;
            BigDecimal shippingPrice;
            Short subscribed;
            Date orderDate;
            String orderStatus;
            Date deliveryDate;
            float duration;
            Calendar calendar;


            address = request.getParameter("Address");
            email = request.getParameter("E-mail");
            warehouse = warehouseFacade.find(Integer.parseInt(request.getParameter("warehouse")));
            productPrice = new BigDecimal(cart.getTotalPrice());
            shippingPrice = new BigDecimal(request.getParameter("Cost"));
            duration = Float.parseFloat(request.getParameter("duration"));


            if (request.getParameter("subscribed") != null) {
                subscribed = 1;
            } else {
                subscribed = 0;
            }

            orderDate = Calendar.getInstance().getTime();
            orderStatus = "queued";

            calendar=Calendar.getInstance();
            calendar.setTime(orderDate);
            calendar.add(Calendar.HOUR,(int)duration);
            deliveryDate = calendar.getTime();

            
            if (user != null) {
                id_user = user.getIdUser();
                order.setIdUser(user);

            }

            order.setAddress(address);
            order.setEMail(email);
            order.setIdWarehouse(warehouse);
            order.setProductPrice(productPrice);
            order.setShippingPrice(shippingPrice);
            order.setSubscribe(subscribed);
            order.setOrderDate(orderDate);
            order.setOrderStatus(orderStatus);
            order.setDeliveryDate(deliveryDate);


            if (cart.getProductList().isEmpty()) {
                out.print("Your cart should not be empty to confirm order<br>");
                out.print("Go to <a href='main.jsp'>main page</a>");
            } else {

                ordersFacade.create(order, cart.getProductList());
                cart.removeAll();


                response.sendRedirect("confirm.jsp?tracking_number=" + order.getTrackingNumber());
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
